#include "../include/RssReader.hpp"

void RssReader::parseRss(const string &fileName)
{
	XMLDocument doc;
	doc.LoadFile(fileName.c_str());
	if (doc.ErrorID())
	{
		return;
	}
	// 获取root节点的指针
	XMLElement *root = doc.FirstChildElement("rss");
	// 获取第一个<item>元素节点的指针
	XMLElement *itemElem =
		root->FirstChildElement("channel")->FirstChildElement("item");

	std::regex re("<.*?>");
	do {
		XMLElement * titleElem = itemElem->FirstChildElement("title");
		const char * title = titleElem->GetText();
		//cout << "title:" << title << endl;

		XMLElement * linkElem = itemElem->FirstChildElement("link");
		const char * link = linkElem->GetText();
		//cout << "link:" << link << endl;


		XMLElement * contentElem1 = itemElem->FirstChildElement("content");
		const char * descript;
		if(contentElem1 == nullptr)
		{
			contentElem1 = itemElem->FirstChildElement("content:encoded");
			if(contentElem1 == nullptr)
			{
				contentElem1 = itemElem->FirstChildElement("description");
				if(contentElem1 == nullptr)
				{
					descript = title;
				}
				else
				{
					descript = contentElem1->GetText();
				}
			}
			else
			{
				descript = contentElem1->GetText();
			}
		}
		else
		{
			descript = contentElem1->GetText();
		}

		if(descript == nullptr)
		{
			descript == title;
		}


		string origin1(descript);

		RssItem item;
		item.title = title;
		item.link = link;
		item.description = string("");
		item.content = std::regex_replace(origin1, re, string(""));
		if(item.content == string(""))
		{
			item.content = title;
		}

		_rss.push_back(item);
	} while((itemElem = itemElem->NextSiblingElement("item")) != nullptr);
	// 寻找第一个标签为<item>的同级节点
}

vector<RssItem> RssReader::getVecRss()
{
	return _rss;
}
